<template>
  <div class="layout layout-100">
    <Layout class="layout-100">

      <Header class="header-cont main__title--top">标准WBS导入</Header>
      <Content class="content-cont">
        <Form ref="formData"
              :model="formData"
              label-position="top"
              :rules="ruleValidate">
          <FormItem label="下载文件（为提高导入的成功率，请下载并使用系统提供的模板)"
                    prop="name">
            <Button type="primary"
                    @click="downMb">下载模板</Button>
          </FormItem>
          <FormItem label="上传文件（仅支持xlsx,xls,文件大小<5M)"
                    prop="name">
            <Poptip trigger="focus">
              <Upload action=''
                      :show-upload-list="false"
                      :before-upload="handleUpload">
                <Input v-model="formData.fileName"
                       prefix="ios-cloud-upload-outline"
                       placeholder="上传文件"
                       style="width: 200px"
                       readonly />
                <Button type="primary"
                        style="margin-left:20px;">选择文件</Button>
              </Upload>
            </Poptip>
          </FormItem>
        </Form>
      </Content>
      <Footer class="footer-cont">
        <Button type="primary"
                @click="saveSubmit('formData')">保存</Button>
        <Button @click="closetab">取消</Button>
      </Footer>
    </Layout>
    <Modal v-model="modal1"
           title="下面数据有误,导入未成功,请修改后[继续导入]:"
           width="80%">
      <Table :columns="columns"
             :data="dataList"
             border
             ref="selection">
        <template v-for="item in columns"
                  slot-scope="{ row, index }"
                  :slot="item.slot">
          <Input v-bind:value="Object.values(row)[item.index]"
                 :title="Object.values(row)[item.index]"
                 :ref="index+Object.keys(row)[item.index]"
                 :maxlength="60"
                 @on-blur="inputModel(index,index+Object.keys(row)[item.index],Object.keys(row)[item.index])"></Input>
        </template>
      </Table>
      <div slot="footer">
        <Button type="text"
                size="large"
                @click="modal1=false">取消</Button>
        <Button type="primary"
                size="large"
                @click="saveItem">继续导入</Button>
      </div>
    </Modal>
  </div>

</template>

<script>
import { mapMutations } from 'vuex'
import apiUrl from '@/api/base'
export default {
  name: 'standardImport',
  data() {
    return {
      modal1: false,
      chacheData: '',
      header: [],
      dataList: [],
      columns: [],
      formData: {
        fileName: '',
        file: null
      },
      ruleValidate: {
        fileName: [{ required: true, message: '请上传文件', trigger: 'blur' }]
      }
    }
  },
  methods: {
    ...mapMutations(['closeTag']),
    closetab() {
      this.closeTag({
        name: this.$route.name,
        params: this.$route.params,
        query: this.$route.query
      })
    },
    handleUpload(file) {
      this.formData.file = file
      this.formData.fileName = file.name
      return false
    },
    // 下载模板
    downMb() {
      window.open(`${apiUrl.imports}${'临建设施导入模板.xls'}`)
    },
    //公用代码--开始
    routerInfo() {
      this.closetab()
      this.$router.push({
        name: 'temporary-facility'
      })
      localStorage.setItem('page', JSON.stringify(this.page))
    },
    dataInfo(header, dataList) {
      this.modal1 = true
      this.columns = []
      header.forEach((item, index) => {
        let obj = {}
        dataList.map((val, num, key) => {
          obj.title = item
          obj.index = index
          obj.key = Object.keys(val)[index]
          obj.slot = Object.keys(val)[index]
        })
        this.columns.push(obj)
        this.dataList = dataList
      })
    },
    //公用代码--结束
    saveSubmit(name) {
      this.$refs[name].validate(valid => {
        if (valid && this.formData.file != null) {
          let formData = new FormData()
          formData.append('file', this.formData.file)
          this.$api.TemporaryFacility.getProfessionalTypeImportExcel(
            formData
          ).then(res => {
            if (res.code == 200) {
              this.formData.file = null
              this.$Message.success(res.message)
              this.routerInfo()
            } else if (res.code === 201) {
              this.$Message.warning(res.message)
              this.header = res.data.header
              this.dataInfo(res.data.header, res.data.dataList)
            } else {
              this.$Message.warning(res.message, res.data.dataList)
            }
          })
        } else {
          this.$Message.warning('请选择要上传的文件')
        }
      })
    },
    //修改后继续导入
    saveItem() {
      let data = {
        data: {
          dataList: this.dataList,
          header: this.header
        }
      }
      this.$api.TemporaryFacility.getProfessionalTypeimportObject(data).then(
        res => {
          if (res.code === 200) {
            this.$Message.success(res.message)
            this.modal1 = false
            this.routerInfo()
          } else if (res.code === 201) {
            this.$Message.warning(res.message)
            this.dataInfo(res.data.header, res.data.dataList)
          } else {
            this.$Message.warning(res.message)
          }
        }
      )
    },
    //失去焦点赋值
    inputModel(index, val, key) {
      let value = this.$refs[val][0].currentValue
      let data = this.dataList[index]
      this.dataList[index][key] = value
    },
    initParams() {
      this.page = this.$route.query
    }
  },
  watch: {
    $route() {
      this.initParams()
      if (this.$route.params.type === 'import') {
        this.formData = {
          fileName: '',
          file: null
        }
      }
    }
  },
  mounted() {
    this.action = ``
  }
}
</script>

<style lang="scss" scoped>
.width50 {
  width: 40%;
}
</style>


